import React ,{useState,useEffect} from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Form, Input,message } from 'antd';
import { loginUser } from '../api/users-api';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthProvider';


const Login = () => {
  const navigate=useNavigate()
  const {handleUserInfo}=useAuth()

  useEffect(()=>{
    localStorage.clear();
  },[])
  const onFinish = async (values) => {
    try{
      let res=await loginUser(values)
      let result=res.data
      if(result.status===1){
        message.success(result.message)
        let userData={
          id:result.data.id,
          login_name:result.data.login_name,
          token:result.data.token
        }
        handleUserInfo(userData)
      }else{
        message.error(result.message)
      }
    }catch(err){
     message.error('登录失败')
    }
  };


  return (
    <div style={{
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      minHeight: '100vh'
    }}>
      <div style={{
        backgroundColor: 'white',
        padding: '40px',
        borderRadius: '8px',
        boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)',
        width: '400px',  // 设置固定宽度
        height: '400px', // 设置相同高度实现正方形
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center'
      }}>
        <h1 style={{ textAlign: 'center', marginBottom: '30px' }}>登录页</h1>
        <Form
          name="login"
          style={{
            maxWidth: '100%',  // 修改为100%以适应卡片宽度
          }}
          onFinish={onFinish}
        >
          <Form.Item
          name="login_name"
          rules={[{required: true,message: '请输入用户名!'}]}
            >
          <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{required: true,message: '请输入密码!'}]}
          >
            <Input prefix={<LockOutlined />} type="password" placeholder="密码" />
          </Form.Item>

          <Form.Item>
            <Button block type="primary" htmlType="submit">
              登 录
            </Button>
            没有账号？ <a href="/register">去注册！</a>
          </Form.Item>
        </Form>
      </div>
    </div>
  );

};
export default Login;